package com.wondersgroup.fjzlpt.org.controller.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.quick.framework.util.FormatDate;
import com.quick.framework.util.LoggerUtil;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.QysjbDao;
import com.wondersgroup.fjzlpt.org.service.inter.jtqy.JtqyService;
import com.wondersgroup.fjzlpt.org.service.inter.timer.AutoRenewService;
import com.wondersgroup.fjzlpt.org.service.inter.timer.JtqyDataImportService;
import com.wondersgroup.fjzlpt.org.service.inter.xymb.XymbService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过springboot执行家庭签约相关定时任务
 * 参考来源：
 *      springboot定时器：https://blog.csdn.net/qq_31001665/article/details/76408929
 *      cron表达式：http://cron.qqe2.com/
 */
@RestController
@EnableScheduling //定时任务类注解
@RequestMapping("jtqyTimeTask")
public class JtqyTimerController {

    @Autowired
    private JtqyService jtqyService;
    @Autowired
    private XymbService xymbService;
    @Autowired
    private QysjbDao qysjbDao;
    @Autowired
    private JtqyDataImportService jtqyDataImportService;
    @Autowired
    private AutoRenewService autoRenewService;

    /**
     * 通过定时任务修改“签约类型”
     * @return JSON对象 { state:1 } || { state:0,info:"失败原因" }
     */
    @RequestMapping("updateQylxByTimedask")
    @Scheduled(cron = "0 0 0 * * ?")
    public JSONObject updateQylxByTimedask(){
        LoggerUtil.info("定时任务updateQylxByTimedask开始执行!!!!!!\n");
        JSONArray resultAry = autoRenewService.queryList(null);
        while (!resultAry.isEmpty() && resultAry.size() > 0){
            for(int i = 0 ; i < resultAry.size() ; i ++){
                JSONObject data = resultAry.getJSONObject(i);
                String qyxxid = data.getString("QYXXID");
                try {
                    autoRenewService.insert(data , null);
                }catch (Exception e){
                    LoggerUtil.info("自动续约失败： " + e.getMessage());
                    data.put("MS" , "自动续约失败： " + e.getMessage());
                    data.put("QYXXID", qyxxid);
                    autoRenewService.update(data , null);
                }
            }
            //当前时间大于23:30则退出当天任务, 等待明天的任务再继续执行
            Date nowTimeHHMM = FormatDate.getDate("HH:mm",FormatDate.getStringDate("HH:mm",new Date()));
            if(nowTimeHHMM.after(FormatDate.getDate("HH:mm","23:30"))) break;

            resultAry = autoRenewService.queryList(new HashMap());
        }
        autoRenewService.xyjlToQy();
        LoggerUtil.info("定时任务updateQylxByTimedask执行结束\n" );
        return null;
    }

    /**
     * 定时任务
     * 解析需要导入的居民签约数据。
     * @return JSON对象 { state:1 } || { state:0,info:"失败原因" }
     */
    @RequestMapping("/importJmQyxx")
    @Scheduled(cron = "0 0 1 * * ?") //定时任务--执行时间(循环时间)； "0 0 0 * * ?" = 每天02:00:00运行一次
    public JSONObject importJmQyxx(){
        LoggerUtil.info("定时任务importJmQyxx(解析需要导入的居民签约信息)开始执行!!!!!! \n");
        //Map map = RequestUtils.GetParameterMap(request);
        JSONArray resultAry = jtqyDataImportService.queryList(null);
        while (!resultAry.isEmpty() && resultAry.size() > 0){
            for(int i = 0 ; i < resultAry.size() ; i ++ ){
                JSONObject item = resultAry.getJSONObject(i);
                try {
                    jtqyDataImportService.importJmQyxx(item );
                }catch (Exception e){
                    LoggerUtil.error(e.getMessage());
                    item.put("ZT" , "03");
                    item.put("BZ" , e.getMessage());
                    jtqyDataImportService.update(item , null);
                }
            }
            //当前时间大于23:30则退出当天任务, 等待明天的任务再继续执行
            Date nowTimeHHMM = FormatDate.getDate("HH:mm",FormatDate.getStringDate("HH:mm",new Date()));
            if(nowTimeHHMM.after(FormatDate.getDate("HH:mm","23:30"))) break;

            resultAry = jtqyDataImportService.queryList(new HashMap());
        }
        LoggerUtil.info("定时任务importJmQyxx(解析需要导入的居民签约信息)执行完成。\n" );
        return  null;
    }

    /**
     * 添加家庭签约协议--对导入的签约数据补充家庭签约协议
     * @return JSON对象 { state:1 } || { state:0,info:"失败原因" }
     */
    @RequestMapping("addJtqyXyInBackstage")
    @Scheduled(cron = "0 0 3 * * ?") //每天00:01:00运行
    public JSONObject addJtqyXyInBackstage(){
        LoggerUtil.info("定时任务addJtqyXyInBackstage开始执行!!!!!!\n");
        JSONObject result = new JSONObject();
        result.put("state","1");
        /**
         * 防止service层面对上一批数据的回滚，所以将逻辑处理放在了该控制层
         */
        try {
            ResultObject ro = new ResultObject();
            //step 1 ：查询启用中家签协议模板
            JSONObject jsonObject = xymbService.getJtqyXymb();

            Document doc = Jsoup.parse(jsonObject.getString("CONTENT"));//通过Jsonp将字符串转为Doc
            Elements jfDiv = doc.select("#jfDiv");//获取id="jfDiv"的元素
            Elements xyhTd = doc.select("#XYH"); //获取协议号的td

            //step 2 : 设置每次处理的数量
            Map map = new HashMap<>();
            int pageSize = 100;
            map.put("pageSize",pageSize);

            //step 3 : 处理数据
            while(true){
                JSONArray qyxxArr = qysjbDao.queryNotXyRecord(map);//查询目标数据

                for(int i=0;i<qyxxArr.size();i++){
                    Map item = qyxxArr.getJSONObject(i);
                    item.put("FWBIDS",item.get("FWBID").toString().replaceAll(",","|"));
                    //在Div中添加2个属性（data和timeTask)
                    String XYH = qysjbDao.queryMaxXyh(item.get("XZQHDM").toString());
                    jfDiv.attr("data", item.toString()).attr("timeTask","1");
                    xyhTd.html(XYH);
                    item.put("CONTENT",doc.select(".panel").toString());

                    //保存协议并更新事件表
                    //item.put("SJLX","01"); //广州库中已存
                    //item.put("BZ","新增签约");
                    item.put("XYH",XYH);
                    item.put("SJGLID","1");
                    item.put("type","update"); //事件表操作类型为： 更新
                    jtqyService.addXyToMongoDbAndRecord(item, ro);

                }
                //1.当查询结果的总数 小于 所求; 2.当前时间大于23:30则退出当天任务, 等待明天的任务再继续执行
                Date nowTimeHHMM = FormatDate.getDate("HH:mm",FormatDate.getStringDate("HH:mm",new Date()));
                if(qyxxArr.size()<pageSize || nowTimeHHMM.after(FormatDate.getDate("HH:mm","23:30"))){
                    break;
                }
            }
        } catch (Exception e) {
            result.put("state","0");
            result.put("info","定时任务：家庭签约协议补充，执行失败！");
            e.printStackTrace();
        }
        LoggerUtil.info("定时任务addJtqyXyInBackstage执行结果:" + result.toJSONString() + "\n");
        return result;
    }
}
